package JUC;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SellticketDemo2 {
    public static void main(String[] args) {
        //并发，多个线程操作同一资源类，把资源类丢到线程
        JUC.out.production.JUC.Ticket ticket = new JUC.out.production.JUC.Ticket();
        //@FunctionInterface 函数式接口 使用lambda表达式 （）->{}

        //创建三个线程操作资源,争抢资源
        new Thread(() -> {
            for (int i = 0; i < 40; i++) ticket.sale();
        }, "A").start();


        new Thread(() -> {
            for (int i = 0; i < 60; i++) ticket.sale();
        }, "B").start();


        new Thread(() -> {
            for (int i = 0; i < 60; i++) ticket.sale();
        }, "C").start();


    }


}

//资源类 OOP
class Ticket {
    //属性
    private int number = 50;
    Lock lock = new ReentrantLock();

    //卖票方法
    //syncnoized 本质：队列，锁
    public void sale() {
        //加锁
        lock.lock();
        //生成代码块

        try {
            //业务代码
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出了" + number-- + "票" + "剩余" + number + "张票");//打印线程

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //解锁
            lock.unlock();
        }
    }
}